package com.atguigu.edu.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.common.EduConfig;
import org.apache.flink.api.java.tuple.Tuple2;
import redis.clients.jedis.Jedis;
import com.atguigu.edu.util.PhoenixUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {
    public static JSONObject getDimInfo(Connection connection,String tableName,String id){
        //优先读取redis
        Jedis jedis = null;
        String redisKey = "DIM:" + tableName + ":" + id;
        String value = null;
        try {
            jedis = JedisUtil.getJedis();
            value = jedis.get(redisKey);;
        } catch (Exception e) {
            System.out.println("jedis异常");
        }

        JSONObject result = null;
        if (value != null){
            //如果redis中有存储的数据  直接读取返回
            result = JSON.parseObject(value);
        } else {
            //如果redis中没有数据   查询Phoenix
            List<JSONObject> dimInfos = getDimInfo(connection, tableName, new Tuple2<>("ID", id));
            if (dimInfos.size() > 0){
                result = dimInfos.get(0);
            //写入到redis中
            jedis.setex(redisKey,3600 * 24,result.toJSONString());
            }
        }
        jedis.close();
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return result;
    }

    public static List<JSONObject> getDimInfo(Connection connection, String tableName, Tuple2<String,String>...tuplle2s){
        StringBuilder sql = new StringBuilder();
        sql.append("select * from  ")
                .append(EduConfig.HBASE_SCHEMA)
                .append(".")
                .append(tableName)
                .append(" where ");
        for (int i = 0; i <tuplle2s.length ; i++) {
            sql.append(tuplle2s[i].f0)
                    .append(" = '")
                    .append(tuplle2s[i].f1)
                    .append("'");
            if (i < tuplle2s.length - 1) {
                sql.append(" and ");
            }
        }
        System.out.println(sql.toString());
        return PhoenixUtil.sqlQuery(connection,sql.toString(),JSONObject.class);
    }

    public static void deleteRedisCache(String tableName,String id){
        String redisKey = "DIM:" +tableName + ":" + id;
        try{
            Jedis jedis = JedisUtil.getJedis();
            jedis.del(redisKey);
            jedis.close();
        }catch (Exception e){
            System.out.println("jedis连接异常");
        }
    }
}
